<?php
namespace common\models\user;

use common\models\Common;

/**
 * This is the model class for table "goods".
 *
 * @property int $id
 * @property string $name
 */
class UserViewLog extends Common
{
    public $endDate = '';

    public static function tableName()
    {
        return '{{%user_view_log}}';
    }

    //获取用户
    public function getUser() {
        return $this->hasOne(User::className(), ['id' => 'user_id']);
    }

    //获取用户
    public function getView() {
        return $this->hasOne(User::className(), ['id' => 'view_user']);
    }
    //获取用户
    public function getLog() {
        return $this->hasOne(static::className(), ['user_id' => 'user_id']);
    }

    /**
     * 浏览记录
     * @param array $user
     * @param array $viewUser
     * @return bool
     */
    public function view($user = [], $viewUser = [])
    {
        if (empty($user) || empty($viewUser)) {
            return true;
        }
        $date = date('Y-m-d H:i:s');

        $viewInfo = static::getOneByWhere(['user_id'=>$user['id'],'view_user'=>$viewUser['id']]);
        if(!empty($viewInfo)){
            $up['view_time'] = $date;
            static::updateData($up,['id'=>$viewInfo['id']]);

        }else{
            $viewData['user_id'] = $user['id'];
            $viewData['user_tx_code'] = $user['tx_code'];
            $viewData['view_user'] = $viewUser['id'];
            $viewData['view_tx_code'] = $viewUser['tx_code'];
            $viewData['view_time'] = $date;
            static::insertData($viewData);
        }

        return true;
    }

}
